<?php
/**
 * 订单管理
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-06
 * Time: 14:58
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\AliPay\App\aop\AliApp;
use App\Libs\Contracts\PayMent\Wxpay\Refund;
use App\Models\Account;
use App\Models\Commodity;
use App\Models\Express;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\User;
use App\Transformers\OrderDetailTransformer;
use Illuminate\Http\Request;
use Fractal;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize;
        $orderNo = $request->orderNo;
        $reciverName = $request->reciverName;
        $phone = $request->phone;
        $orderStatus = $request->orderStatus;
        $excel = $request->excel;
        $orderType = $request->orderType;
        $goodType=$request->goodType;
        $sql = Order::select('t1.*','t2.phone as userPhone')
           ->from((new Order())->getTable().' as t1')
            ->leftJoin((new User())->getTable().' as  t2','t1.userId','=','t2.userId');

        if ($orderStatus) {
            $sql->where('orderStatus', $orderStatus);
        }
        if ($orderType) {
            $sql->where('orderType', $orderType);
        }
        if ($goodType) {
            if($goodType == "USER"){
                $sql->whereIn("goodType",['USER','MALL']);
            }else{
                $sql->where('goodType',$goodType);
            }

        }
        if ($orderNo) {
            $sql->where('orderNo', 'like', '%' . $orderNo . '%');
        }
        if ($reciverName) {
            $sql->where('reciverName', 'like', '%' . $reciverName . '%');
        }
        if ($phone) {
            $sql->where('t2.phone', 'like', '%' . $phone . '%');
        }

        if($excel){
            $data = $sql->orderBy('createTime', 'desc')->get()->toArray();
            $result = [['订单号', '下单时间', '金额', '数量', '收件人姓名', '联系电话', '收货地址', '商品名称', '订单状态','支付方式','下单手机号'],];
            $i = 0;
            foreach ($data as $value) {
                $orderType = str_replace(['WX','ALI'],['微信','支付宝'],$value['orderType']);
                $orderStatusStr = str_replace(['NONPAYMENT','ORDERFINISH','WAITDELIVER','WAITRECEIVE','CANCEL','REFUND'],
                    ['待付款','交易完成','待发货','待收货','取消订单','已退款'],$value['orderStatus']);
                $address = $value['province'].$value['city'].$value['area'].$value['detail'];
                $result[$i + 1] = [$value['orderNo'], $value['createTime'], round($value['totalPrice'] / 100.0,2), $value['amount'], $value['reciverName'] ,
                    $value['phone'], $address,$value['goodTitle'],$orderStatusStr,$orderType,$value['userPhone']];
                $i++;
            }
            $status = Excel::create("订单列表", function ($excel) use ($result) {
                $excel->sheet('order', function ($sheet) use ($result) {
                    $sheet->setFontFamily('宋体');
                    $sheet->rows($result);

                });
            });
            return $status->export('xls');
        }
        $data = $sql->orderBy('createTime', 'desc')->paginate($pageSize)->toArray();
        $result['totalNum'] = $data['total'];
        $result['orderList'] = $data['data'];
        return $this->apiResponse($result);
    }
    public function  examination(Request $request)
    {
        $pageSize = $request->pageSize ? $request->pageSize : 20;
        $page = $request->page? $request->page : 1;
        $orderNo=$request->orderNo;
        $userName=$request->userName;
        $phone=$request->phone;
        $excel=$request->excel;
        $orderStatus=$request->orderStatus;
       $sql=Order::select('t1.orderNo','t1.createTime','t1.totalPrice','t1.goodTitle','t1.orderStatus',
           't2.phone','t1.userName','t1.reservationPhone','t1.reservationDate','t2.nickname')
       ->from((new Order())->getTable() . ' as t1')
       ->leftJoin((new User ())->getTable()  .  ' as  t2','t1.userId','=','t2.userId');
        if($orderNo){
            $sql->where('t1.orderNo','like','%'.$orderNo.'%');
       }
        if($userName){
            $sql->where('t1.userName','like','%'.$userName.'%')->orWhere('t2.nickname','like','%'.$userName.'%');

        }
        if($phone){
           $sql->where('t1.reservationPhone','=',$phone)->orWhere('t2.phone','=',$phone);
        }

        if($orderStatus)  {
            $sql->where('t1.orderStatus',$orderStatus);
        }
        if($excel){
            $data = $sql->where('t1.goodType','EXAMINATION')->orderBy('createTime', 'desc')->get()->toArray();

            $result = [['订单号', '下单时间', '套餐金额 ', '体检套餐', '订单状态', '购买人昵称', '购买人手机号', '体检人信息', '体检预约手机号','预约时间'],];
            $i = 0;
            foreach ($data as $value) {
                $orderStatus = str_replace(['UN_EXAMINATION',' EXAMINATION'],['未体检','已体检'],$value['orderStatus']);
                $result[$i + 1] = [$value['orderNo'], $value['createTime'], round($value['totalPrice'] / 100.0,2), $value['goodTitle'], $orderStatus,
                    $value['nickname'], $value['phone'],$value['userName'],$value['reservationPhone'],$value['reservationDate']];
                $i++;
            }
            $status = Excel::create("体检订单列表", function ($excel) use ($result) {
                $excel->sheet('order', function ($sheet) use ($result) {
                    $sheet->setFontFamily('宋体');
                    $sheet->rows($result);

                });
            });
            return $status->export('xls');
        }
        $data=$sql->where('t1.goodType','EXAMINATION')->orderBy('t1.createTime','desc')->paginate($pageSize)->toArray();
        $result['orderList']=$data['data'];
        $result['totalNum']=$data['total'];
        return $this->apiResponse($result);


    }
    public function  examinationshow($orderNo)
    {

       $data=Order::select('t1.orderNo','t1.createTime','t1.totalPrice','t1.goodTitle','t1.orderStatus','t2.nickname',
           't2.phone','t1.userName','t1.reservationPhone','t1.reservationDate','t1.idCard')
           ->from((new Order())->getTable() . ' as t1')
           ->leftJoin((new User ())->getTable()  .  ' as  t2','t1.userId','=','t2.userId')
       ->where('t1.orderNo',$orderNo)
       ->first();

        return $this->apiResponse($data);
    }

    public function  examinationOk(Request $request)
    {
        $orderNo=$request->orderNo;
       $data=Order::where('orderNo',$orderNo)->update(
           [
             'orderStatus'=>'EXAMINATION'
       ]);
       return $this->apiResponse(true);
    }

    public function show($orderNo)
    {
        $data = Order::select('t1.*','t2.phone as userPhone')
            ->from((new Order())->getTable().' as t1')
            ->leftJoin((new User())->getTable().' as  t2','t1.userId','=','t2.userId')
            ->where('orderNo',$orderNo)->first();
        return $this->apiResponse($data);
    }
    public function logistic(Request $request)
    {
        $data = Express::select('e_name as name')->orderByDesc('id')->get()->toArray();
        return $this->apiResponse($data);
    }


    public function deliver(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'orderNo' => 'required',
            'deliverName' => 'required',
            'deliverNo' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $order = Order::where('orderNo',$data['orderNo'])->first();
        if($order['deliverNo']){
            $status = Order::where(['orderNo' => $data['orderNo']])
                ->update(['deliverName' => $data['deliverName'],
                    'deliverNo' => $data['deliverNo']]);
        }else{
            $status = Order::where(['orderNo' => $data['orderNo'], 'orderStatus' => 'WAITDELIVER'])
                ->update(['orderStatus' => 'WAITRECEIVE', 'deliverName' => $data['deliverName'],
                    'deliverNo' => $data['deliverNo'],
                    'deliveryTime' => date("Y-m-d H:i:s", time())]);
        }

        return $this->apiResponse(true);
    }
    public function refund(Request $request)
    {
        $orderNo = $request->orderNo;
        $order = Order::where('orderNo',$orderNo)->first();
        if($order['orderStatus'] == "NONPAYMENT" || $order['orderStatus'] == "CANCEL"||
            $order['orderStatus'] == "REFUND"){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //退款
        $result['orderNo'] = $order['orderNo'];
        $result['refundNo'] = "R".$order['orderNo'];
        $result['totalPrice'] = $order['totalPrice'];
        $result['refundPrice'] = $order['totalPrice'];

        if($order['orderType'] == "WX"){
            $model = new Refund();
            $status = $model->refund($result);
        }else{
            $result['totalPrice'] = $order['totalPrice']  / 100;
            $result['refundPrice'] = $order['totalPrice']  / 100;
            $result['refundReason'] = "退款";
            $model = new AliApp();
            $status = $model->refund($result);
        }
        if($status){
            Order::where(['orderNo' => $orderNo])->update(['orderStatus' => 'REFUND']);
        }else{
            return $this->apiResponse('', config('errorCode.CANCEL_ORDER_FAILED'));
        }
        return $this->apiResponse(true);
    }

}